package org.jamin.lending.service.impl;

import org.jamin.lending.domain.entity.Auser;
import org.jamin.lending.domain.entity.BorrowInfo;
import org.jamin.lending.domain.entity.ManagerMessage;
import org.jamin.lending.domain.form.manger.BorrowInfoForm;
import org.jamin.lending.domain.form.manger.VerifyBorrowForm;
import org.jamin.lending.repository.BorrowInfoRepository;
import org.jamin.lending.repository.ManagerMessageRepository;
import org.jamin.lending.service.BorrowService;
import org.jamin.lending.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;

@Service
public class BorrowServiceImpl implements BorrowService {

    @Autowired
    private BorrowInfoRepository borrowInfoRepository;

    @Autowired
    private ManagerMessageRepository managerMessageRepository;

    @Autowired
    private MessageService messageService;

    @Override
    public Page<BorrowInfo> findBorrowList(BorrowInfoForm borrowInfoForm) {
        Pageable pageable = new PageRequest(borrowInfoForm.getPageSize(),borrowInfoForm.getPageSize());
        return this.borrowInfoRepository.findAll(pageable);
    }

    @Override
    public Page<BorrowInfo> findBorrowListByStatus(BorrowInfoForm borrowInfoForm, BorrowInfo.Status status) {
        Pageable pageable = new PageRequest(borrowInfoForm.getPageCurrent(),borrowInfoForm.getPageSize());
        return this.borrowInfoRepository.findByStatus(status,pageable);
    }

    /**
     * 创建借款标，并发送站内信到管理员
     * @param borrowInfo
     */
    @Override
    public void createBorrow(BorrowInfo borrowInfo,Auser auser) {
        borrowInfo.setStatus(BorrowInfo.Status.PRELIMINARY);
        this.borrowInfoRepository.save(borrowInfo);
        ManagerMessage managerMessage = new ManagerMessage();
        managerMessage.setMessage(auser.getUsername()+"申请发布借款，请审核");
        managerMessage.setAuser(auser);
        this.managerMessageRepository.save(managerMessage);
    }

    @Override
    public void preliminaryBorrow(VerifyBorrowForm verifyBorrowForm,Auser auser) {
        BorrowInfo borrowInfo = this.borrowInfoRepository.findOne(verifyBorrowForm.getBorrowId());
        String message = "";
        if(verifyBorrowForm.isPass()){
            borrowInfo.setStatus(BorrowInfo.Status.PUBLISHER);
            message = "借款初审成功";
        }else{
            borrowInfo.setStatus(BorrowInfo.Status.REFUSE);
            message = "借款初审失败";
        }
        borrowInfo.setPreliminaryUser(auser);
        borrowInfo.setPreliminaryTime(new Timestamp(System.currentTimeMillis()));
        borrowInfo.setPreliminaryDescription(verifyBorrowForm.getMessage());
        this.borrowInfoRepository.save(borrowInfo);
        this.messageService.sendManagerMessage(auser,message);
    }

}
